package com.dfy.service.impl;

import com.dfy.dto.ReviewDTO;
import com.dfy.entity.Review;
import com.dfy.entity.User;
import com.dfy.mapper.ReviewMapper;
import com.dfy.mapper.UserMapper;
import com.dfy.service.ReviewService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReviewServiceImpl implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<ReviewDTO> getSpotReviews(Long spotId, int page, int size) {
        int offset = (page - 1) * size;
        List<Review> reviews = reviewMapper.findBySpotId(spotId, offset, size);
        return reviews.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public int getSpotReviewCount(Long spotId) {
        return reviewMapper.countBySpotId(spotId);
    }

    private ReviewDTO convertToDTO(Review review) {
        User user = userMapper.findById(review.getUserId());
        // 如果找不到用户，使用默认值
        if (user == null) {
            user = new User();  // 使用无参构造函数
            user.setUserId(review.getUserId());
            user.setUsername("已删除用户");
            user.setAvatar("default-avatar.png");
        }

        List<String> images = new ArrayList<>();
        if (review.getImages() != null && !review.getImages().isEmpty()) {
            try {
                images = objectMapper.readValue(review.getImages(), new TypeReference<List<String>>() {});
            } catch (Exception e) {
                // 如果解析失败，使用空列表
            }
        }

        return ReviewDTO.builder()
                .id(review.getId())
                .user(ReviewDTO.UserInfo.builder()
                        .userId(user.getUserId())
                        .username(user.getUsername())
                        .avatar(user.getAvatar() != null ? user.getAvatar() : "default-avatar.png")  // 添加默认值
                        .build())
                .rating(review.getRating())
                .content(review.getContent())
                .images(images)
                .createdAt(review.getCreatedAt())
                .build();
    }
} 